package com.yuyang.wifi.base;

import android.annotation.SuppressLint;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.MaterialDialog;
import com.yuyang.wifi.R;
import com.yuyang.wifi.activitys.login.WeChatLoginActivity;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.dialog.NewLoadingDialog;
import com.yuyang.wifi.utils.ActivityAllManager;
import com.yuyang.wifi.utils.DeviceUtils;
import com.yuyang.wifi.utils.EmptyUtils;
import com.yuyang.wifi.utils.Skip;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.eventbus.BaseEvent;
import com.yuyang.wifi.utils.eventbus.BaseEventManager;
import com.yuyang.wifi.utils.eventbus.BaseEventObserver;
import com.yuyang.wifi.utils.network.HttpErrorHandlerImp;
import com.gyf.barlibrary.ImmersionBar;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by wangce on 16/1/15.
 */
public abstract class BaseActivity extends com.trello.rxlifecycle.components.support.RxFragmentActivity
        implements BaseEventObserver {

    protected List<SuperSubject> superSubjectList = new ArrayList<>();
    protected HttpErrorHandlerImp httpErrorHandlerImp;
    protected DialogHandlerImp dialogHandlerImp;

    InstallReceiver installReceiver;
    AppManager appManager;
    private ImmersionBar mImmersionBar;
    private Unbinder bind;

    @SuppressLint({"MissingSuperCall", "SourceLockedOrientationActivity"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (!DeviceUtils.getManufacturer().equals("OPPO")) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }

        try {
            //用户手动修改权限，app进程杀掉,监测到以后，自动重启app
//            if (savedInstanceState != null) {
//
//                Log.e("time", "time:=====");
//
//                Intent intent = new Intent(BaseActivity.this, SplashActivity.class);
//                //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                startActivity(intent);
//                ActivityManager.getInstance().finishAllActivity();
//            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("error : " + e.getLocalizedMessage());
        }

        super.onCreate(savedInstanceState);
        View baseView = LayoutInflater.from(this).inflate(getLayoutResId(), null, false);
        setContentView(baseView);
        bind = ButterKnife.bind(this);
        //注册EventBus
        BaseEventManager.register(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        appManager = AppManager.getInstance();
        appManager.addActivity(this);
        ActivityAllManager.getInstance().onCreate(this);
        httpErrorHandlerImp = new HttpErrorHandlerImp(this);
        dialogHandlerImp = new DialogHandlerImp(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.DOWNLOAD_COMPLETE");
        installReceiver = new InstallReceiver();
        registerReceiver(installReceiver, filter);
        //引用三方库，statusBarColor设置状态栏的颜色，statusBarDarkFont设置状态栏图标颜色true黑色，false白色,
        // application theme设置为Theme.AppCompat.Light.NoActionBar,去除原有标题栏和状态栏，自由定义状态栏标题栏
        mImmersionBar = ImmersionBar.with(this).navigationBarColor(R.color.white).statusBarColor(R.color.transparent).statusBarDarkFont(true);
        mImmersionBar.keyboardEnable(true).navigationBarWithKitkatEnable(false).init();
        initActionBar();
        initContentView();
    }

    protected abstract void initActionBar();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        appManager.removeActivty(this);
        ActivityAllManager.getInstance().onDestroy(this);
        unRegisterObserver();
        dismissDialog();
        dismissProgressDialog();
        //销毁EventBus
        BaseEventManager.unregister(this);
        //解绑
        bind.unbind();
        if (installReceiver != null) {
            unregisterReceiver(installReceiver);
        }
        if (mImmersionBar != null) {
            mImmersionBar.destroy();//必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
        }
    }


    protected void initBar() {

    }

    protected void initBusObserver() {

    }

    protected void initButtonObserver() {

    }


    protected <T> SuperSubject<T> registerObserver(String tag, Class<T> clazz) {
        SuperSubject<T> superSubject = RxBus.getInstance().register(tag, clazz);
        superSubjectList.add(superSubject);
        return superSubject;
    }


    protected <T> SuperSubject<T> registerObserver(String tag, Class<T> clazz, final SuperSubject.onSubscribe<T> tCall) {
        SuperSubject<T> superSubject = RxBus.getInstance().register(tag, clazz);
        superSubject.observeOnMainThread(tCall);
        superSubjectList.add(superSubject);
        return superSubject;
    }


    protected void unRegisterObserver() {
        if (!EmptyUtils.isEmpty(superSubjectList)) {
            for (SuperSubject superSubject : superSubjectList) {
                RxBus.getInstance().unRegister(superSubject);
            }
        }
    }


    protected MaterialDialog progressDialog;

    public void showProgressDialog(String message) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        progressDialog = new MaterialDialog.Builder(this)
                .content(message)
                .canceledOnTouchOutside(false)
                .progress(true, 0)
                .build();
        progressDialog.show();
    }


    public void dismissProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    //没有更多了
    protected View showFooterNoMoreData() {
        View footerView = LayoutInflater.from(this).inflate(R.layout.item_footer_no_more, null);
        footerView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        return footerView;
    }

    protected synchronized void showDialog() {
        dialogHandlerImp.showDialog();
    }

    protected synchronized void dismissDialog() {
        dialogHandlerImp.dismissDialog();
    }


    protected abstract int getLayoutResId();

    protected abstract void initContentView();

    @Subscribe
    @Override
    public void onMessageEventMain(BaseEvent baseEvent) {
        String tagString = baseEvent.getTagString();
        Bundle bundle = (Bundle) baseEvent.getData();
        switch (tagString) {
            case "token_lose_efficacy"://token失效
                deleteAuth();
                String tokenLose = SpUtil.find(AppConstant.KEY_TOKEN_LOSE);
                if (TextUtils.isEmpty(tokenLose)) {
                    Log.e("token", "错误吗===402");
                    SpUtil.saveOrUpdate(AppConstant.KEY_TOKEN, "");
                    SpUtil.saveOrUpdate(AppConstant.KEY_USER_ID, "");
                    Log.e("token", "失效==: " + "1111111");
                    SpUtil.saveOrUpdate(AppConstant.KEY_TOKEN_LOSE, "first");
                    ActivityAllManager.getInstance().finishAllActivity();
                    Skip.toActivity(this, WeChatLoginActivity.class);
                }
                break;
            case "no_permission"://无权限认证

                break;
        }
    }

    @Subscribe
    @Override
    public void onMessageEventPost(BaseEvent baseEvent) {

    }

    @Subscribe
    @Override
    public void onMessageEventBackground(BaseEvent baseEvent) {

    }

    @Subscribe
    @Override
    public void onMessageEventAsync(BaseEvent baseEvent) {

    }


    public void onClick(View view) {

    }

    // loading
    protected NewLoadingDialog newLoadingDialog;

    /**
     * 显示正在加载。。。
     */
    public void showLoadingDialog() {

        if (null != newLoadingDialog) {
            newLoadingDialog.show();
        } else {
            newLoadingDialog = new NewLoadingDialog(this);
            newLoadingDialog.show();
        }
    }


    /**
     * 取消加载
     */
    public void dismissLoadingDialog() {
        if (null != newLoadingDialog) {
            newLoadingDialog.dismiss();
        }
    }


    public void showUploadDownLoadingDialog() {

        if (null != newLoadingDialog) {
            newLoadingDialog.show();
        } else {
            newLoadingDialog = new NewLoadingDialog(this);
            newLoadingDialog.setCanceledOnTouchOutside(false);
            newLoadingDialog.show();
        }
    }


    /**
     * 取消加载
     */
    public void dismissUploadDownLoadingDialog() {
        if (null != newLoadingDialog) {
            newLoadingDialog.dismiss();
        }
    }

    private void deleteAuth() {
        UMShareAPI.get(this).deleteOauth(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
